package cn.fl.capital.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.condition.CapAdvFundQueryCondition;
import cn.fl.capital.service.ICapAdvFundRvtService;
import cn.fl.capital.vo.CapAdvFundVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.ref.fncprjbscinfo.service.IFncPrjBscInfoService;
import cn.fl.ref.fncprjbscinfo.transform.FncPrjBscInfoVOTransform;
import cn.fl.ref.fncprjbscinfo.vo.FncPrjBscInfoVO;
import cn.fl.system.constant.SysLogConstant;
import com.alibaba.fastjson.JSONObject;
import fl.ref.fncprjbscinfo.condition.FncPrjBscInfoQueryCondition;
import fl.ref.fncprjbscinfo.constant.FncPrjBaseInfoConstant;
import fl.ref.fncprjbscinfo.dto.FncPrjBscInfoDTO;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description: 垫款资金冲销管理 控制层
 */
@Controller
@RequestMapping("/capital/capAdvFundRvt")
public class CapAdvFundRvtController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(CapAdvFundRvtController.class);

    /**
     * CapAdvFund 服务层BEAN
     */
    @Autowired
    private ICapAdvFundRvtService capAdvFundRvtService;
    @Autowired
    private IFncPrjBscInfoService fncPrjBscInfoService;
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "加载CapAdvFundRvt列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("capital/capAdvFund/capAdvFundRvtList");
        return mav;
    }

    /**
     * 到新增页面
     */
    @RequestMapping(value = "/toAddPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toAddPage", "加载CapAdvFundRvt Add冲销指令页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("capital/capAdvFund/capAdvFundRvtDtl");
        String paySchNo = request.getParameter("paySchNo");
        String minAdvClAmt = request.getParameter("minAdvClAmt");
        String maxAdvClAmt = request.getParameter("maxAdvClAmt");

        if(StringUtils.isNotBlank(paySchNo)){
            mav.addObject("paySchNo",paySchNo);
        }
        if(StringUtils.isNotEmpty(minAdvClAmt)){
            mav.addObject("minAdvClAmt", DecimalUtils.convertYuanToFen(Double.parseDouble(minAdvClAmt)));
        }else{
            mav.addObject("minAdvClAmt", 0L);
        }
        if(StringUtils.isNotEmpty(maxAdvClAmt)){
            mav.addObject("maxAdvClAmt", DecimalUtils.convertYuanToFen(Double.parseDouble(maxAdvClAmt)));
        }

        return mav;
    }

    //加载数据字典数据、传值等 ？
    public void prepare(HttpServletRequest request, ModelAndView mav) {

    }

    /**
     * 初始化列表 垫款资产
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initRvtPayList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initCapAdvFundList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        CapAdvFundQueryCondition qc = new CapAdvFundQueryCondition();
        //再融资项目ID
        String fncPrjId = request.getParameter("fncPrjId");
        if (StringUtils.isNotEmpty(fncPrjId)) {
            qc.setFncPrjId(Long.parseLong(fncPrjId));
        }
        page.setCondition(qc);

        BaseLogUtils.info(logger, "initCapAdvFundRvtList", "初始化垫款资产列表页面数据.DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        Pager pager = this.capAdvFundRvtService.searchListPage(page);
        List<CapAdvFundVO> list = (List<CapAdvFundVO>) pager.getResultList();
        ListPageVO<CapAdvFundVO> listPage = new ListPageVO<CapAdvFundVO>(list, pager.getTotalCount());
        return listPage;
    }

    /**
     * 初始化列表 核销付款
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initRvtFundList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initRvtFundList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        CapAdvFundQueryCondition qc = new CapAdvFundQueryCondition();
        //再融资项目ID
        String fncPrjId = request.getParameter("fncPrjId");
        if (StringUtils.isNotEmpty(fncPrjId)) {
            qc.setFncPrjId(Long.parseLong(fncPrjId));
        }
        page.setCondition(qc);

        BaseLogUtils.info(logger, "initRvtFundList", "初始化待冲销付款资金列表页面数据.DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        Pager pager = this.capAdvFundRvtService.searchRvtFundListPage(page);
        List<CapAdvFundVO> list = (List<CapAdvFundVO>) pager.getResultList();
        ListPageVO<CapAdvFundVO> listPage = new ListPageVO<CapAdvFundVO>(list, pager.getTotalCount());
        return listPage;
    }

    /**
     * 初始化列表 核销支付表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initRvtPaySchList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initRvtPaySchList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        CapAdvFundQueryCondition qc = new CapAdvFundQueryCondition();
        //再融资项目ID
        String fncPrjId = request.getParameter("fncPrjId");
        if (StringUtils.isNotEmpty(fncPrjId)) {
            qc.setFncPrjId(Long.parseLong(fncPrjId));
        }
        page.setCondition(qc);

        BaseLogUtils.info(logger, "initRvtPaySchList", "初始化待冲销支付表列表页面数据.DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        Pager pager = this.capAdvFundRvtService.searchRvtPaySchListPage(page);
        List<CapAdvFundVO> list = (List<CapAdvFundVO>) pager.getResultList();
        ListPageVO<CapAdvFundVO> listPage = new ListPageVO<CapAdvFundVO>(list, pager.getTotalCount());
        return listPage;
    }

    /**
     * 保存并发送垫款冲销资金
     */
    @RequestMapping(value = "/batchAddRvtFund.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object batchAddRvtFund(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        try {
            CapAdvFundQueryCondition condition = new CapAdvFundQueryCondition();
            DataResultVO resultVO = this.capAdvFundRvtService.batchAddRvtFund(condition);
            if(BaseConstant.IS_YESNO_NO==resultVO.getSuccess()){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(resultVO.getInfo());
            }
        } catch (BaseException e) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + e.getMessage());
            BaseLogUtils.info(logger, "batchAddRvtFund", "批量新增垫款冲销资金失败.ERROR:" + e.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception e) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + e.getMessage());
            BaseLogUtils.info(logger, "batchAddRvtFund", "批量新增垫款冲销资金失败ERROR:" + e.getMessage(), CurrentThreadContext.getCurrentUserName());
        }

        return result;
    }

    /**
     * 获取请求参数
     *
     * @param request 请求
     * @return
     */
    private CapAdvFundVO getRequestParamForCapAdvFund(HttpServletRequest request) throws BaseException {
        //获取参数
        String id = request.getParameter("id");//主键
        String code = request.getParameter("code");//资金编号 垫款（DK+ID）冲销（HB+ID）
        String batchId = request.getParameter("batchId");//批次号
        String cstId = request.getParameter("cstId");//客户ID
        String cstNm = request.getParameter("cstNm");//客户名称
        String paySchId = request.getParameter("paySchId");//支付表ID
        String paySchNo = request.getParameter("paySchNo");//支付表号
        String payPd = request.getParameter("payPd");//期次
        String payAmt = request.getParameter("payAmt");//金额
        String payBkId = request.getParameter("payBkId");//付款银行账户ID(SYS_BK_ACC_INFO表ID、BANK_ACC_INFO表ID)
        String payAccNo = request.getParameter("payAccNo");//付款账号
        String payAccNm = request.getParameter("payAccNm");//付款账户
        String payBkNm = request.getParameter("payBkNm");//付款开户银行
        String payBkNo = request.getParameter("payBkNo");//付款银行开户行号
        String dueBkId = request.getParameter("dueBkId");//收款银行账户ID(SYS_BK_ACC_INFO表ID、BANK_ACC_INFO表ID)
        String dueAccNo = request.getParameter("dueAccNo");//收款账户
        String dueAccNm = request.getParameter("dueAccNm");//收款户名
        String dueBkNm = request.getParameter("dueBkNm");//收款开户银行
        String dueBkNo = request.getParameter("dueBkNo");//收款银行开户行号
        String capAttrCd = request.getParameter("capAttrCd");//资金属性(CAP0027 ): 1.租赁人还款 2.垫款 3.租赁人还款红冲
        String advTm = request.getParameter("advTm");//垫款时间
        String retTm = request.getParameter("retTm");//垫款回拨时间
        String fundStsCd = request.getParameter("fundStsCd");//垫款/回拨状态  0.未提交 1.已提交
        String relFundId = request.getParameter("relFundId");//关联垫款资金ID
        String penaltyRate = request.getParameter("penaltyRate");//日罚息率(%)
        String capUseCost = request.getParameter("capUseCost");//资金使用成本
        String buOrgCd = request.getParameter("buOrgCd");//(支付表)所属事业部
        String fundRem = request.getParameter("fundRem");//备注
        String version = request.getParameter("version");//版本

        //验证参数并赋值
        CapAdvFundVO entity = new CapAdvFundVO();
        //entity.setCode(code);//资金编号 垫款（DK+ID）冲销（HB+ID）
        //entity.setBatchId(batchId);//批次号
        //entity.setCstId(cstId);//客户ID
        //entity.setCstNm(cstNm);//客户名称
        //entity.setPaySchId(paySchId);//支付表ID
        //entity.setPaySchNo(paySchNo);//支付表号
        //entity.setPayPd(payPd);//期次
        //entity.setPayAmt(payAmt);//金额
        //entity.setPayBkId(payBkId);//付款银行账户ID(SYS_BK_ACC_INFO表ID、BANK_ACC_INFO表ID)
        //entity.setPayAccNo(payAccNo);//付款账号
        //entity.setPayAccNm(payAccNm);//付款账户
        //entity.setPayBkNm(payBkNm);//付款开户银行
        //entity.setPayBkNo(payBkNo);//付款银行开户行号
        //entity.setDueBkId(dueBkId);//收款银行账户ID(SYS_BK_ACC_INFO表ID、BANK_ACC_INFO表ID)
        //entity.setDueAccNo(dueAccNo);//收款账户
        //entity.setDueAccNm(dueAccNm);//收款户名
        //entity.setDueBkNm(dueBkNm);//收款开户银行
        //entity.setDueBkNo(dueBkNo);//收款银行开户行号
        //entity.setCapAttrCd(capAttrCd);//资金属性(CAP0027 ): 1.租赁人还款 2.垫款 3.租赁人还款红冲
        //entity.setAdvTm(advTm);//垫款时间
        //entity.setRetTm(retTm);//垫款回拨时间
        //entity.setFundStsCd(fundStsCd);//垫款/回拨状态  0.未提交 1.已提交
        //entity.setRelFundId(relFundId);//关联垫款资金ID
        //entity.setPenaltyRate(penaltyRate);//日罚息率(%)
        //entity.setCapUseCost(capUseCost);//资金使用成本
        //entity.setBuOrgCd(buOrgCd);//(支付表)所属事业部
        //entity.setFundRem(fundRem);//备注
        //entity.setVersion(version);//版本

//		if (StringUtils.isBlank(name)) {
//            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "名称不能为空.");
//      }
//      if (StringUtils.isNotBlank(num)) {
//          if (!StringUtils.isUnsignedNumeric(num)) {
//                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写正确的数字.");
//          }
//      }

        Date tm = new Date();
        if (StringUtils.isNotBlank(id)) {
            entity.setId(Long.valueOf(id));
            entity.setMdfTm(tm);
            entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
        } else {
            entity.setCrtTm(tm);
            entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
            //entity.setCrtUsrOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前用户组织机构代码
            //entity.setOrgCd(CurrentThreadContext.getCurrentBuOrgCd());//事业部组织机构代码
        }

        return entity;
    }

    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initFncPrjList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initFncPrjList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        FncPrjBscInfoQueryCondition qc = new FncPrjBscInfoQueryCondition();
        String condition = request.getParameter("condition");
        if (StringUtils.isNotBlank(condition)) {
            JSONArray conditionArray = JSONArray.fromObject(condition);
            for (Object object : conditionArray) {
                net.sf.json.JSONObject jsonObject = (net.sf.json.JSONObject) object;
                if ("fncprjnm".equals(String.valueOf(jsonObject.get("field")))) {
                    qc.setFncprjnm(String.valueOf(jsonObject.get("value")));
                }
            }
        }
        //正常
        qc.setFncprjstcd(7);
        page.setCondition(qc);

        Pager pager = this.fncPrjBscInfoService.searchListPage(page);
        List<FncPrjBscInfoVO> list = FncPrjBscInfoVOTransform.toVOList((List<FncPrjBscInfoDTO>) pager.getResultList());
        ListPageVO<FncPrjBscInfoVO> listPage = new ListPageVO<FncPrjBscInfoVO>(list, pager.getTotalCount());
        return listPage;
    }

    /**
     * 设置产品基本信息中关于字典项信息
     *
     * @param listVO
     */
    private void setListVOWithDicInfo(List<FncPrjBscInfoVO> listVO) {
        if (CollectionUtils.isEmpty(listVO)) {
            return;
        }
        String sysCd = CurrentThreadContext.getCurrentSysCd();
        String orgCd = CurrentThreadContext.getCurrentOrgCd();
        Map<String, String> astIdlist = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, FncPrjBaseInfoConstant.FNC_PRJ_AST_ID);
        for (FncPrjBscInfoVO vo : listVO) {
            //资产占用种类
            if (astIdlist.containsKey(vo.getAstId())) {
                vo.setAstNm(astIdlist.get(vo.getAstId()));
            }
        }
    }
}

